<template>
    <div class="root">
        <div class="mapSection">
            <el-form label-width="80px">
                <el-row>
                    <el-col :span="10">
                        <el-form-item label="搜索地址">
                            <el-input type="text" id="searchAddress" v-model="searchAddress" placeholder="请输入地址"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="14">
                        <el-form-item label="当前地址">
                            <el-input v-model="addressInfo.address" placeholder="请输入内容">
                                <template slot="prepend">
                                    {{ addressInfo.province }}{{ addressInfo.city }}{{ addressInfo.district }}
                                </template>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <!-- 百度地图 -->
            <div id="map-container" style="width: 100%; height: 100%;"></div>
        </div>
        <div class="userSection">

        </div>

    </div>
</template>
  
<script>
export default {
    data() {
        return {
            ak: 'DC8tZKXH4dAvOo03ECNjG60joDH8cizt',
            pass: '',
            // 搜索地址
            searchAddress: "",
            // 地址信息
            addressInfo: {
                // 经度
                longitude: "",
                // 纬度
                latitude: "",
                // 省
                province: "",
                // 市
                city: "",
                // 区
                district: "",
                // 详细地址
                address: ""
            },
            map: null,
            geoc: null,
            list: [{
                name: '合肥测试',
                value: [113.410789, 23.118483],
                icon: require("@/assets/logo.png"),
                click: true // 是否点击弹窗
            }]
            ,
            userList: [],

        }
    },
    methods: {
        /** 打开地图选择 */
        loadData() {
            this.initBaiduMap();
        },
        // 初始化百度地图
        initBaiduMap() {
            let that = this;

            this.$nextTick(function () {
                console.log('初始化地图 start---------');

                var map = new BMap.Map("map-container", { enableMapClick: false }) // 创建地图实例
                var geoc = new BMap.Geocoder();
                this.map = map;
                this.geoc = geoc;


                var point = new BMap.Point(113.410789, 23.118483); // 设置中心点坐标
                map.centerAndZoom(point, 13); // 地图初始化，同时设置地图展示级别
                map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
                that.fetchInitPoint();
                that.initClick()
                that.initSearch()
            })
        },
        // 初始点位--------------------------------------------------------------------
        fetchInitPoint() {
            //  地图上覆盖点/自定义图标/点击点弹窗显示信息
            this.list.forEach(item => {
                // 1、指定坐标放置自定义图标
                var myIcon = new BMap.Icon(item.icon, new BMap.Size(40, 40));
                var marker = new BMap.Marker(new BMap.Point(...item.value), {
                    icon: myIcon
                });
                marker.disableMassClear();
                this.map.addOverlay(marker); //!!!
                // 2、图标下面添加lable文字描述
                var opts = {
                    position: new BMap.Point(...item.value), // 指定文本标注所在的地理位置
                    offset: new BMap.Size(0, 25) // 设置文本偏移量
                };
                // 自定义文本：创建文本标注对象
                if (item.name) {
                    // 添加员工数量显示
                    //let img = require('./img/num-bg.png') // 若使用背景图需要这样引入，然后使用变量
                    var label = new BMap.Label(
                        `<div class="flexObj">
                            <b class="${item.num && item.num != 0 ? 'show' : 'hide'}" style="background-color:red;border-radius: 10px; color: #fff; padding:2px 4px 3px; font-size: .0833rem;">
                                ${item.name}
                            </b>
                        </div>`,
                        opts);

                    // 自定义标注样式
                    label.setStyle({
                        color: '#1a73e8',
                        borderColor: 'transparent',
                        backgroundColor: "transparent",
                        fontSize: 13 + 'px',
                        height: 25 + 'px',
                        lineHeight: 22 + 'px',
                        fontFamily: '微软雅黑',
                        transform: 'translateX(-50%)'
                    });
                    label.disableMassClear()
                    this.map.addOverlay(label);//!!!
                }
                //3、 添加点击事件弹窗事件
                if (item.click) {
                    // 创建图文信息窗口
                    var opts = {
                        width: 450,     // 信息窗口宽度
                        offset: {
                            width: 100,
                            height: 0
                        }
                    }
                    var sContent = `<div class="pb-20">
                    </div>`;
                    var infoWindow = new BMap.InfoWindow(sContent, opts);
                    // marker添加点击事件
                    marker.addEventListener('click', function (e) {
                        e.domEvent.stopPropagation();
                        this.openInfoWindow(infoWindow); // 弹窗弹出
                    })
                }
            })
        },
        // 非初始点位点击--------------------------------------------------------------------
        initClick() {
            /** 点击地图创建坐标事件Start */
            // 添加地图点击事件
            const _this = this;
            this.map.addEventListener("click", function (e) {

                var click = e.point; // 点击的坐标
                _this.map.clearOverlays(); // 移除地图上的标注

                var marker = new BMap.Marker(click); // 创建标注
                console.log('initClick-----', click, marker);
                _this.map.addOverlay(marker); // 将标注添加到地图中 //!!!
                _this.getLocation(click.lng, click.lat) //获取点位信息
            })
        },
        getLocation(long, lat) {
            var x = long;
            var y = lat;
            var token = this.ak;

            // var pass= this.pass;

            //  v2 版本    
            var url = 'http://api.map.baidu.com/geocoder/v2/?location= ' + y + "," + x + '&output=json&ak=' + token + '&pois=1'
            //  v3 版本 
            // var url = "http://api.map.baidu.com/reverse_geocoding/v3/?ak=" + token +
            // "&output=json&coordtype=wgs84ll&location=" + y + "," + x + "&mcode=" + pass;

            // this.$u.get(url).then((res) => { //  当前封装了方法    自用的话，直接拿url请求就好
            //     if (data.status == 0) {
            //         var address = data.result.formatted_address;
            //         var description = data.result.sematic_description;
            //         alert(address + description);
            //     }
            // });

            this.showLocationInfo({}, [x, y])
        },
        showLocationInfo(info, location) {

            function ComplexCustomOverlay(lon, lat, text, index, type, id) {
                this._point = new BMap.Point(lon, lat);
                this._lon = lon;
                this._lat = lat;
                this._text = text;
            }

            ComplexCustomOverlay.prototype = new BMap.Overlay();

            ComplexCustomOverlay.prototype.initialize = function (map) {
                this._map = map;
                const div = this._div = document.createElement("div");
                div.style.zIndex = BMap.Overlay.getZIndex(500);
                div.style.position = "absolute";
                div.style.background = "white";
                div.style.overflow = "hidden";
                div.style.borderRadius = "3px";
                div.id = "overLayPoint"
                div.innerHTML = `
                <div style=" background: white;
                    width: 200px;
                    padding: 4px 6px;"
                >
                    <div style="padding-bottom: 4px;">
                        确认添加点位吗？
                    </div>
                    <div style="">
                        位置：${this._text || '无点位信息'}
                    </div>
                </div>
                `
                let button = document.createElement("div");
                button.innerHTML = `
                <div style="
                    cursor:pointer;
                    padding: 3px 5px;
                    text-align: center;
                    background-color: white;
                    color: black;
                    border: 2px solid #4CAF50;
                    border-radius:5px;">
                    确定
                </div>
                `
                div.appendChild(button)
                button.onclick = (e) => { //禁止事件冒泡
                    console.log('ComplexCustomOverlay', e);
                    const oEvent = e || event;
                    oEvent.cancelBubble = true;
                    //获取地图上所有的覆盖物，找到自己删除
                    const allOverlay = this._map.getOverlays();
                    for (const item of allOverlay) {
                        if (item instanceof ComplexCustomOverlay) {
                            this._map.removeOverlay(item);
                        }
                    }
                };
                map.getPanes().labelPane.appendChild(div);
                return div;
            }
            ComplexCustomOverlay.prototype.draw = function () {
                var map = this._map;
                // 根据地理坐标转换为像素坐标，并设置给容器
                var pixel = map.pointToOverlayPixel(this._point);
                this._div.style.left = pixel.x - 50 + "px";
                this._div.style.top = pixel.y - 120 + "px";
            }
            let myOverlay = new ComplexCustomOverlay(location[0], location[1], 'text',);
            this.map.addOverlay(myOverlay);

        },
        // 搜索-------------------------------------------------------------
        initSearch() {
            const _this = this;
            /** 搜索地址Start */
            // 建立一个自动完成的对象
            var ac = new BMap.Autocomplete({
                input: "searchAddress",
                location: this.map,
            });
            // 鼠标点击下拉列表后的事件
            ac.addEventListener("onconfirm", function (e) {
                _this.map.clearOverlays();
                var local = new BMap.LocalSearch(_this.map, {
                    // 智能搜索
                    onSearchComplete: function (res) {
                        let poi = res.getPoi(0); // 获取第一个智能搜索的结果
                        var searchpt = poi.point; // 获取坐标
                        _this.map.centerAndZoom(searchpt, 16);
                        _this.map.addOverlay(new BMap.Marker(searchpt));
                        that.geocAddress(searchpt);
                    }
                });
                // 搜索词
                var searchValue = e.item.value;
                local.search(
                    searchValue.province +
                    searchValue.city +
                    searchValue.district +
                    searchValue.street +
                    searchValue.business
                )
            });
            /** 搜索地址End */
        },
        // 逆向解析地址
        geocAddress(point) {
            let that = this;
            var geoc = new BMap.Geocoder();
            geoc.getLocation(point, function (geocInfo) {
                // 设置基本信息
                var addressInfo = geocInfo.addressComponents;
                that.addressInfo.longitude = point.lng;
                that.addressInfo.latitude = point.lat;
                that.addressInfo.province = addressInfo.province;
                that.addressInfo.city = addressInfo.city;
                that.addressInfo.district = addressInfo.district;
                let address = addressInfo.street + addressInfo.streetNumber;
                if (geocInfo.surroundingPois.length > 0) {
                    address = address + geocInfo.surroundingPois[0].title;
                }
                that.addressInfo.address = address;
            });
        },



    },
}
</script>
<style scoped lang="scss" >
.root {
    height: 100%;
    display: flex;
}

.mapSection {
    flex: 1;
}

.userSection {
    min-height: 200px;
    width: 200px;
    height: 100%;
}

::v-deep .BMap_Marker {
    background-size: contain !important;

    img {
        height: 100%;
        width: 100%;
    }
}

::v-deep .baidu-map {

    .BMap_bottom {
        display: none;
    }
}

::v-deep .BMap_shadow {
    display: none;
}

::v-deep .BMap_pop {

    &>div,
    &>img:nth-child(10) {
        display: none;
        overflow: unset;
    }

    &>div:nth-child(9) {
        display: block;
        overflow: unset;
    }

    &>div:nth-child(8) {
        /*display: block;*/
    }

    .BMap_top {
        display: none;
    }

    .BMap_center {
        background: transparent;
        border: none;
        position: sticky !important;
        height: 100%;
    }
}

::v-deep .BMap_bubble_content {
    background: rgba(0, 0, 0, .5);
    border-radius: 5px;
    padding: 20px;

    .info-window {
        padding-right: 8px;
        width: 100%;
        max-height: 280px;
        overflow: auto;

        .el-divider {
            background: #ccccccbf;
        }

        .address {
            color: #fff;
        }
    }

    //自定义滚动条样式
    .info-window::-webkit-scrollbar {
        width: 6px;
        height: 1px;
    }

    .info-window::-webkit-scrollbar-thumb {
        border-radius: 6px;
        -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        background: #535353;
    }

    .info-window::-webkit-scrollbar-track {
        -webkit-box-shadow: inset 0 0 5px rgba(0, 0, 0, 0.2);
        border-radius: 6px;
        background: #EDEDED;
    }
}
</style>
  
  